#!/usr/bin/env bash
#
# Restarts Amazon virtual machines.

prog=$(basename $0)
DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)

. "$DIR"/vms_ids

usage()
{
	echo "usage: $prog [stop|start|restart|status] [instanceid ...]" 1>&2
	echo "No instanceids restarts all AWS machines" 1>&2
	echo "'freebsd' maps to instanceid $freebsdid" 1>&2
	echo "'netbsd' maps to instanceid $netbsdid" 1>&2
	echo "'ubuntu' maps to instanceid $ubuntuid" 1>&2
	echo "'windows' maps to instanceid $windowsid" 1>&2
	exit 1
}

[ -z "$1" ] && usage

. "$DIR"/vms_shared

instanceids="$2"
if [ -n "$instanceids" ] ; then
	[ "$instanceids" = "ubuntu" ] && instanceids=$ubuntuid
	[ "$instanceids" = "windows" ] && instanceids=$windowsid
	[ "$instanceids" = "freebsd" ] && instanceids=$freebsdid
	[ "$instanceids" = "netbsd" ] && instanceids=$netbsdid
else
	instanceids=$(get_all_instanceids)
fi

if [ "$1" = "stop" ] ; then
	stop_instanceids "$instanceids" || fail
elif [ "$1" = "start" ] ; then
	start_instanceids "$instanceids" || fail
elif [ "$1" = "restart" ] ; then
	stop_instanceids "$instanceids" || fail
	start_instanceids "$instanceids" || fail
elif [ "$1" = "status" ] ; then
	get_states "$instanceids" || fail
else
	usage
fi

get_details "$instanceids"

exit 0
